/* global Cesium viewer Y_BASE_URL */
import dataQueryFunc from '../dataQueryFunc';
import { delEmpty } from 'U/dealwithParam.js';
import { postQuery } from 'S/interface.js';
import axios from 'axios';
import dataCenterBus from 'U/dataCenterBus';

const constant = 180 / Math.PI;
const queryUrl = Y_BASE_URL + 'common/query';
const queryAllUrl = Y_BASE_URL + 'common/queryAll';
const queryChecked = Y_BASE_URL + 'common/queryChecked';

const url = {
    standardProduct: {
        url: queryUrl,
        allUrl: queryAllUrl,
        checkedUrl: queryChecked,
    },
};

let data = {
    standardProduct: {
        total: 0,
        pageCount: 0,
        currentPage: 0,
        rows: [],
    },
};

let stopListeningType = '';
let cancelToken = null;
let cancelAllToken = null;
let queryType = 'standardProduct';

class Param {
    constructor() {
        this.standardProduct = {
            isOnlyChoice: false,
        };
        this.standardProduct.param = {
            pageSize: 18,
            currentPage: 1,
            // isAsc: 'desc',
        };
    }
    /**
     * 塞入参数
     * @param {string} name :参数名称
     * @param {object} value ：参数值
     * @param {boolean} isMapMove ：是否移动视野适配查询结果
     * @param {boolean} noImmediately 是否暂时不查询
     */
    setParam(name, value, isMapMove, noImmediately) {
        this[name] = value;
        if (
            name !== 'currentPage' &&
            name !== 'ids' &&
            !this[queryType].isOnlyChoice &&
            name !== 'valueTime' &&
            !noImmediately
        ) {
            this[queryType].param.currentPage = 1;
            this.queryData('', isMapMove);
        }
    }

    /**
     * 根据查询条件请求数据列表
     * @param {Boolean} flag 是否不请求融合结果
     * @param {Boolean} isMapMove 是否移动视野适配查询的数据
     */
    queryData(flag, isMapMove) {
        cancelToken && cancelToken('取消请求');
        this.queryParam.types =
            this.queryParam.types &&
            this.queryParam.types
                .toString()
                .replace('REF', 'GFWFV')
                .replace('ALBEDO', 'Albedo')
                .split(',');
        let param = {
            url: url[queryType].url,
            param: delEmpty(this.queryParam),
            cancelToken: new axios.CancelToken(function executor(c) {
                cancelToken = c;
            }),
        };
        postQuery(param)
            .then(contentList => {
                Object.assign(data[queryType], contentList.data);
                if (isMapMove) {
                    if (contentList.data && contentList.data.rows.length > 0) {
                        let latLng = [];
                        contentList.data.rows.forEach(item => {
                            let latLngArr = Cesium.Cartesian3.fromDegreesArray([
                                item.bottomleftlongitude,
                                item.bottomleftlatitude,
                                item.bottomrightlongitude,
                                item.bottomrightlatitude,
                                item.topleftlongitude,
                                item.topleftlatitude,
                                item.toprightlongitude,
                                item.toprightlatitude,
                            ]);
                            latLng.push(...latLngArr);
                        });
                        dataQueryFunc.positioningLatLngArr(latLng);
                    } else {
                        console.error('未查到数据');
                    }
                }
            })
            .catch(e => {});

        if (!flag) {
            cancelAllToken && cancelAllToken('取消全部数据请求');
            dataQueryFunc.removeLayer();
            let param = {
                url: url[queryType].allUrl,
                param: this.queryParam,
                cancelToken: new axios.CancelToken(function executor(c) {
                    cancelAllToken = c;
                }),
            };
            postQuery(param)
                .then(spaceData => {
                    dataQueryFunc.createDataArea(spaceData.data);
                })
                .catch(e => {});
        }
    }

    /**
     * 请求所有已选择的数据列表
     */
    queryCheckedData() {
        cancelToken && cancelToken('取消请求');
        cancelAllToken && cancelAllToken('取消全部数据请求');

        let param = {
            url: url[queryType].checkedUrl,
            param: this.queryParam,
            cancelToken: new axios.CancelToken(function executor(c) {
                cancelAllToken = c;
            }),
        };
        postQuery(param)
            .then(contentList => {
                Object.assign(data[queryType], contentList.data);
            })
            .catch(e => {});
    }
    /**
     * 是否查询已选择的数据
     */
    set isOnlyChoice(val) {
        this[queryType].isOnlyChoice = val;
    }

    /**
     * 设置当前页数，根据状态调用相应的查询方法
     */
    set currentPage(val) {
        this[queryType].param.currentPage = val;
        if (this[queryType].isOnlyChoice) {
            this.queryCheckedData();
        } else {
            this.queryData(false);
        }
    }
    /**
     * 名称改变
     */
    set nameParam(val) {
        this[queryType].param.name = val;
    }
    /**
     * 根据时间的排序方法
     */
    set isAsc(val) {
        this[queryType].param.isAsc = val;
        delete this[queryType].param.isCloud;
    }

    /**
     * 类型条件筛选
     */
    set checkedType(val) {
        if (val.length > 0) {
            this[queryType].param.types = val;
        } else {
            delete this[queryType].param.types;
        }
    }
    /**
     * 分辨率条件筛选
     */
    set imageGsd(val) {
        if (val.length > 0) {
            this[queryType].param.resolution = val;
        } else {
            delete this[queryType].param.resolution;
        }
    }
    /**
     * 查询的时间范围
     */
    set valueTime(val) {
        if (val.length > 1 && new Date(val[0]) < new Date(val[1])) {
            this[queryType].param.startTime = getStrTime(val[0]);
            this[queryType].param.endTime = getStrTime(val[1]);
        }
        if (val.length < 2 && this[queryType].param.startTime && this[queryType].param.endTime) {
            delete this[queryType].param.startTime;
            delete this[queryType].param.endTime;
        }
        this[queryType].param.currentPage = 1;
        if (!this[queryType].isOnlyChoice) {
            this.queryData(false);
        }
    }
    /**
     * 查询目标的位置参数
     */
    set geoParam(val = {}) {
        if (val.isMapMoveCenter) {
            Object.keys(data).forEach(item => {
                this[item].param.geo = val.geo;
                this[item].param.geoType = val.geoType;
            });
        } else {
            this[queryType].param.geo = val.geo;
            this[queryType].param.geoType = val.geoType;
            delete this[queryType].param.sceneid;
        }
    }
    /**
     * 已选择是数据id
     */
    set ids(val) {
        this[queryType].param.ids = val;
    }
    /**
     * 是否进行视野监听
     */
    set isListeningMapMove(val) {
        this._isListeningMapMove = val;
    }
    /**
     * 获取查询参数
     */
    get queryParam() {
        return Object.assign(this[queryType].param);
    }
    /**
     * 获取查询参数
     */
    queryAllParam() {
        let param = this[queryType].param;
        return param;
    }
    /**
     * 获取查询结果的数据列表
     */
    getDataList() {
        return data.standardProduct;
    }
    /**
     * 重置查询条件
     */
    resetQueryParam() {
        delete this[queryType].param.name;
        delete this[queryType].param.types;
        delete this[queryType].param.resolution;
        delete this[queryType].param.startTime;
        delete this[queryType].param.endTime;
        delete this[queryType].param.geo;
        delete this[queryType].param.geoType;

        this[queryType].param.currentPage = 1;
        if (!this._isOnlyChoice) {
            this.queryData();
        }
    }
    /**
     * 监听视野移动
     */
    getViewCenter() {
        try {
            let intersection = viewer.camera.pickEllipsoid({
                x: viewer.container.clientWidth / 2,
                y: viewer.container.clientHeight / 2,
            });
            if (!intersection) {
                return;
            }
            let cartographic = Cesium.Cartographic.fromCartesian(intersection);
            if (cartographic) {
                let point =
                    'POINT(' +
                    cartographic.longitude * constant +
                    ' ' +
                    cartographic.latitude * constant +
                    ')';
                this.setParam('geoParam', {
                    geo: point,
                    geoType: 'wkt',
                    isMapMoveCenter: true,
                });
                dataCenterBus.$emit('positions', [
                    {
                        longitude: cartographic.longitude * constant,
                        latitude: cartographic.latitude * constant,
                    },
                ]);
            }
        } catch (error) {
            console.log(error);
        }
    }
    /**
     * 控制是否进行视野监听
     * @param {Boolean} val 是否开启事业监听
     */
    isListeningMapMoveFun(val, geoType) {
        if (geoType && stopListeningType !== geoType) {
            return;
        }
        val = Cesium.defined(val) ? val : this._isListeningMapMove;
        this._isListeningMapMove = val;
        if (val) {
            if (this.cameraMoveEvent) {
                return;
            }
            this.cameraMoveEvent = viewer.camera.moveEnd.addEventListener(() => {
                this.getViewCenter();
            });
            this.getViewCenter();
        } else {
            this.cameraMoveEvent && this.cameraMoveEvent();
            this.cameraMoveEvent = null;
        }
    }
    setStopListeningType(val) {
        stopListeningType = val;
    }
}
/**
 * 处理的时间参数
 * @param {Date} pldTime 时间参数
 */
function getStrTime(pldTime) {
    return (
        pldTime.getFullYear() +
        '-' +
        oneToTwo(pldTime.getMonth() + 1) +
        '-' +
        oneToTwo(pldTime.getDate() + ' 00:00:00')
    );
}
/**
 * 时间格式一个数字转两个数字
 */
function oneToTwo(str) {
    let resStr = str;
    if (String(str).length < 2) {
        resStr = '0' + String(str);
    }
    return resStr;
}

export default new Param();
